package com.cloud.goal.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloud.goal.model.Habit;
import com.cloud.goal.model.HabitDaily;
import com.cloud.platform.IDao;
import com.cloud.platform.util.Constants;
import com.cloud.platform.util.DateUtil;
import com.cloud.platform.util.StringUtil;

@Component
public class HabitService {

	@Autowired
	private IDao dao;
	
	/**
	 * search today's daily habit info
	 * 
	 * @param userId
	 * @return
	 */
	public List<String> searchDailyInfo(String userId) throws Exception {
	
		if(StringUtil.isNullOrEmpty(userId)) {
			return new ArrayList();
		}
		
		String hql = "select habitId from HabitDaily where uid = ? and createTime = ?";
		
		return dao.getAllByHql(hql, new Object[] {userId, DateUtil.parseDate(new Date())});
	}
	
	/**
	 * save daily habit
	 * 
	 * @param userId
	 * @param dailyInfo
	 */
	public void saveDailyHabit(String userId, String dailyInfo) throws Exception {
		
		if(StringUtil.isNullOrEmpty(userId, dailyInfo)) {
			return;
		}
		
		Date today = new Date();
		today = DateUtil.parseDate(today);
		
		// remove today's daily habit info
		String hql = "delete from HabitDaily where createTime = ?";
		dao.removeByHql(hql, today);
		
		// add daily habit
		String[] habits = dailyInfo.split(",");
		
		for(String h : habits) {
			HabitDaily hd = new HabitDaily();
			
			hd.setId(Constants.getID());
			hd.setUid(userId);
			hd.setHabitId(h);
			hd.setCreateTime(today);
			
			dao.saveObject(hd);
		}
	}
	
	/**
	 * get user's all habits
	 * 
	 * @param userId
	 * @return
	 */
	public List<Habit> searchHabits(String userId) {
		
		if(StringUtil.isNullOrEmpty(userId)) {
			return new ArrayList();
		}
		
		String hql = "from Habit where uid = ? order by sn";
		return dao.getAllByHql(hql, userId);
	}
	
	/**
	 * save habit
	 * 
	 * @param userId
	 * @param habit
	 */
	public void saveHabit(String userId, Habit habit) {
		
		if(StringUtil.isNullOrEmpty(userId)) {
			return;
		}
		
		habit.setId(Constants.getID());
		habit.setUid(userId);
		
		dao.saveObject(habit);
	}
}
